// DeliveryModal.jsx（子组件）
import React, { forwardRef, useImperativeHandle, useState } from "react";
import { Modal, Radio, Button, Dialog, Space, Toast } from "antd-mobile";
import addressApi from '@/api/iap/address'
import orderApi from "@/api/iap/order";
import { getUser } from "@/utils/localStorage";

import { BankcardOutline, RightOutline } from "antd-mobile-icons";
import { useNavigate } from "react-router-dom";
import './index.css';
//  使用 forwardRef 接收父组件传递的 ref
const DeliveryModal = forwardRef(({ cartIds, activityId, pickUpStation }, ref) => {
  const [visible, setVisible] = useState(false); // 子组件自己控制显示状态
  const [address, setAddresses] = useState(null) //地址状态
  const [deliveryType, setDeliveryType] = useState('2'); // 选择自提或地址
  const [pickUp, setPickUp] = useState('') //自提信息
  const [loadingCreate, setLoadingCreate] = useState(false);
  const navigate = useNavigate();

  //  定义子组件的 open 方法
  const open = (data = { deliveryType: '', addressId: '' }) => {
    console.log('data', data)
    console.log('pickUpStation', pickUpStation)

    setVisible(true);
    if (data.deliveryType) {
      setDeliveryType(data.deliveryType.toString())
    }
    if (data.addressId) {
      getAddressById(data.addressId)
    } else {
      getDefaultAddress()
    }

  };

  //  使用 useImperativeHandle 暴露方法给父组件的 ref
  useImperativeHandle(ref, () => ({
    open,
    close: () => setVisible(false),
  }));

  //获取id地址
  const getAddressById = async (id) => {
    let res = await addressApi.address_get({ id })
    setAddresses(res.data)
    console.log('地址', res.data)
  }

  //获取默认地址
  const getDefaultAddress = async () => {
    let res = await addressApi.address_get_default()
    setAddresses(res.data)
    console.log('默认地址', res.data)
  }

  // 创建订单
  const createOrder = async () => {


    let data = {
      activityId: activityId,
      cartIds: cartIds,
      deliveryType: deliveryType, // 1快递发货 2用户自提
      addressId: deliveryType == '1' ? (address ? address.id : null) : null, //快递发货时，地址ID不能为空
      pickUpStore: deliveryType == '2' ? pickUpStation : null, //自提：自提点信息
      receiverName: deliveryType == '2' ? (getUser().nickname || null) : null //自提：收货人飞书名称
    }
    setLoadingCreate(true)
    try {
      let res = await orderApi.order_create(data)
      if (res.msg == '') {
        Toast.show({ content: '订单创建成功', duration: 1000, icon: 'success' });
        navigate('/order')
      } else {
        Toast.show({ content: res.msg, duration: 2000, icon: 'fail' });
      }

    } finally {
      setLoadingCreate(false)
    }
  }



  return (
    <Dialog visible={visible} className="choose-address-modal"
      title='选择地址'
      content={
        <>
          <Radio.Group value={deliveryType} onChange={val => setDeliveryType(val)} style={{ width: '100%' }}>
            <Space direction='vertical'>
              <Radio value='2'>用户自提</Radio>

              {deliveryType == '2' && <>
                {pickUpStation ? <div className="pick-up" >
                  {pickUpStation}
                </div> :
                  <div>暂无自提点配置</div>}
              </>
              }
              <Radio value='1'>快递发货</Radio>
            </Space>
          </Radio.Group>

          <div style={{ marginTop: '10px' }}>
            {deliveryType == '1' && <>
              {address ?
                <div key={address.id} className="address-card" onClick={() => { navigate(`/address?type=select&cartIds=${cartIds.toString()}&addressId=${address.id}&activityId=${activityId}`) }}>
                  <div style={{ flex: 1 }}>
                    {/* 地址头部：收货人+电话+默认标识 */}
                    <div className="address-header-info" style={{ marginBottom: '2px' }}>
                      <div className="receiver-info">
                        <span className="receiver-name">{address.name}</span>
                        <span className="receiver-phone">{address.mobile}</span>
                      </div>
                    </div>
                    {/* 地址内容：省市区+详细地址 */}
                    <div className="address-content" style={{ marginBottom: '0' }}>
                      <p className="address-area" style={{ marginBottom: '2px' }}>{address.areaName}</p>
                      <p className="address-detail s2">{address.detailAddress}</p>
                    </div>
                  </div>
                  <div style={{ padding: '8px' }}>
                    <RightOutline fontSize={24} />
                  </div>
                  <div>
                  </div>
                </div> :
                <div>
                  暂无默认地址，去  {<Button color='primary' onClick={() => { navigate(`/address?type=select&cartIds=${cartIds.toString()}&addressId=-1&activityId=${activityId}`) }} fill='none' style={{ padding: '0' }}> 选择地址</Button>}
                </div>
              }
            </>
            }


          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '20px' }}>
            <Button style={{ width: '48%' }} onClick={() => { setVisible(false) }}>取消</Button>
            <Button style={{ width: '48%' }} onClick={createOrder} loading={loadingCreate} color='primary'
              disabled={deliveryType == 1 && !address?.id}
            >确认</Button>
          </div>
        </>
      }
    />
  );
});

export default DeliveryModal;